package com.youlai.boot.factory.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.factory.converter.CustomersConverter;
import com.youlai.boot.factory.mapper.CustomersMapper;
import com.youlai.boot.factory.model.entity.Customers;
import com.youlai.boot.factory.model.form.CustomersForm;
import com.youlai.boot.factory.model.query.CustomersQuery;
import com.youlai.boot.factory.model.vo.CustomersVO;
import com.youlai.boot.factory.service.CustomersService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 客户服务实现类
 *
 * @author youlaitech
 * @since 2025-07-06 00:42
 */
@Service
@RequiredArgsConstructor
public class CustomersServiceImpl extends ServiceImpl<CustomersMapper, Customers> implements CustomersService {

    private final CustomersConverter customersConverter;

    /**
    * 获取客户分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<CustomersVO>} 客户分页列表
    */
    @Override
    public IPage<CustomersVO> getCustomersPage(CustomersQuery queryParams) {
        Page<CustomersVO> pageVO = this.baseMapper.getCustomersPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取客户表单数据
     *
     * @param id 客户ID
     * @return 客户表单数据
     */
    @Override
    public CustomersForm getCustomersFormData(Long id) {
        Customers entity = this.getById(id);
        return customersConverter.toForm(entity);
    }
    
    /**
     * 新增客户
     *
     * @param formData 客户表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveCustomers(CustomersForm formData) {
        Customers entity = customersConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新客户
     *
     * @param id   客户ID
     * @param formData 客户表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateCustomers(Long id,CustomersForm formData) {
        Customers entity = customersConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除客户
     *
     * @param ids 客户ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteCustomerss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的客户数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
